package main

import "fmt"

func main02() {
	arr := [5]int{24, 57, 13, 69, 80}
	fmt.Println("排序前:", arr)
	BubbleSort(&arr)
	fmt.Println("排序后:", arr)

	//simpleFind()
	fmt.Println(binarySearch(&arr, 0, len(arr)-1, 81))
}

func binarySearch(arr *[5]int, startIndex int, endIndex int, value int) int {
	if startIndex > endIndex {
		return -1
	}

	var middleIndex = (startIndex + endIndex) / 2
	if (*arr)[middleIndex] > value {
		return binarySearch(arr, startIndex, middleIndex-1, value)
	} else if (*arr)[middleIndex] < value {
		return binarySearch(arr, middleIndex+1, endIndex, value)
	} else {
		return middleIndex
	}
}

//顺序查找
func simpleFind() {
	names := [...]string{"白眉鹰王", "金毛狮王", "紫衫龙王", "青翼蝠王"}
	var name = ""
	fmt.Println("请输入要查找的人名")
	fmt.Scanln(&name)

	var index = -1
	for i := 0; i < len(names); i++ {
		if names[i] == name {
			index = i
			break
		}
	}
	if index == -1 {
		fmt.Println("没找到")
	} else {
		fmt.Println("找到了，索引位置为：", index)
	}
}

func BubbleSort(ptr *[5]int) {
	var tmp int
	var loopCnt = 0
	// i这层表示需要比较的轮次，是数组长度-1次
	for i := 0; i < len(ptr)-1; i++ {
		var alreadySort = true
		loopCnt += 1
		// 两两比较
		for j := 0; j < len(ptr)-1-i; j++ {
			if (*ptr)[j] > (*ptr)[j+1] {
				tmp = (*ptr)[j]
				(*ptr)[j] = (*ptr)[j+1]
				(*ptr)[j+1] = tmp
				alreadySort = false //如果有交换，说明还需要进行下一轮比较
			}
		}
		if alreadySort {
			break
		}
	}
	fmt.Println("loopCnt=", loopCnt)
}
